﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit.Abstractions;
using Xunit;

namespace 初级算法.其他
{
    public class 位1的个数
    { 
        public class Solution
        {
            /// <summary>
            /// 191. 位1的个数 https://leetcode.cn/problems/number-of-1-bits/
            /// </summary>
            /// <param name="n"></param>
            /// <returns></returns>
            public int HammingWeight(uint n)
            {
                BitArray bitArray = new BitArray(BitConverter.GetBytes(n));
                int num = 0;
                for (var i = 0; i < bitArray.Length; i++)
                {
                    if (bitArray[i]) num++;
                }
                return num;
            }
            /// <summary>
            /// 执行用时：48 ms, 在所有 C# 提交中击败了63.95%的用户
            /// 内存消耗：15.7 MB, 在所有 C# 提交中击败了6.98%的用户
            /// </summary>
            /// <param name="n"></param>
            /// <returns></returns>
            public int HammingWeight2(uint n)
            {
                return Convert.ToString(n, 2).Count(c => c == '1');
            }


        }
        ITestOutputHelper output;

        public 位1的个数(ITestOutputHelper output)
        {
            this.output = output;
        }


        [Fact]
        public void Test1()
        {

            uint un1 = 0b00000000000000000000000000001011;
            uint un2 = 0b00000000000000000000000010000000;
            uint un3 = 0b11111111111111111111111111111101;
            Solution S = new Solution();

            output.WriteLine("" + S.HammingWeight(un1));
            output.WriteLine("" + S.HammingWeight(un2));
            output.WriteLine("" + S.HammingWeight(un3));
            output.WriteLine("");
            output.WriteLine("" + S.HammingWeight2(un1));
            output.WriteLine("" + S.HammingWeight2(un2));
            output.WriteLine("" + S.HammingWeight2(un3));
        }
    }
}
